public class Solution1754 {
    public String largestMerge(String word1, String word2) {
        StringBuilder stringBuilder=new StringBuilder();
        int i=0,j=0;
        while (i<word1.length() && j<word2.length()){
            if (word1.charAt(i)>word2.charAt(j) || word1.charAt(i)==word2.charAt(j) && word1.substring(i+1).compareTo(word2.substring(j+1))>0){
                stringBuilder.append(word1.charAt(i));
                i++;
            }else{
                stringBuilder.append(word2.charAt(j));
                j++;
            }
        }
        while (i<word1.length()){
            stringBuilder.append(word1.charAt(i));
            i++;
        }
        while (j<word2.length()){
            stringBuilder.append(word2.charAt(j));
            j++;
        }
        return stringBuilder.toString();
    }

    public static void main(String[] args) {
        System.out.println(new Solution1754().largestMerge("cabaa","bcaaa"));
    }
}
